//
//  SlideOptionView.m
//  Foundation
//
//  Created by 新庭 on 2019/10/20.
//

#import "SlideOptionView.h"
#import "FXCategories.h"
#import "UIView+FView.h"
#import "SlideOptionCell.h"

@interface SlideOptionViewSlider ()

@property (nonatomic, strong) UIImage *normalImg;
@property (nonatomic, strong) UIImage *highlightedImg;

@end
@implementation SlideOptionViewSlider

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state {
    switch (state) {
        case UIControlStateHighlighted:
            self.highlightedImg = image;
            if (self.isHighlighted) {
                self.image = image;
            }
            break;
            
        default:
            self.normalImg = image;
            self.image = image;
            break;
    }
}

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];
    
    self.image = highlighted ? self.highlightedImg : self.normalImg;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    UIColor *bgColor = [UIColor jk_gradientFromColor:[UIColor whiteColor] toColor:self.highlighted ? self.tintColor : [UIColor lightGrayColor] withHeight:self.jk_height];
    self.backgroundColor = bgColor;
}

@end

#pragma mark - SlideOptionView

@interface SlideOptionView () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray<SlideOptionCell *> *options;
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, UIColor *> *colors;

@end

@implementation SlideOptionView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _options = [NSMutableArray array];
        _colors = [NSMutableDictionary dictionary];
        
        [self addSubview:self.slider];
        [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.mas_offset(0);
        }];
        UIPanGestureRecognizer *gr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMove:)];
        gr.delegate = self;
        [self addGestureRecognizer:gr];
        
        self.clipsToBounds = YES;
        
        [self prepareSubviews];
    }
    return self;
}

- (void)prepareSubviews {
    [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    UIColor *selectColor = [UIColor blackColor];
    if (@available(iOS 13.0, *)) {
        selectColor = [UIColor labelColor];
    }
    [self setTitleColor:selectColor forState:UIControlStateSelected];
}

- (void)setItems:(NSArray<OptionItem *> *)items {
    [super setItems:items];
    
    [self relayoutLabels];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    // 取消前一个的选中
    if (self.selectedIndex < self.options.count) {
        self.options[self.selectedIndex].selected = NO;
    }
    
    if (self.options.count <= selectedIndex || self.options[selectedIndex].hidden) {
        return;
    }
    
    [super setSelectedIndex:selectedIndex];
    
    self.options[self.selectedIndex].selected = YES;
    [self.slider mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.leading.trailing.top.bottom.mas_equalTo(self.options[selectedIndex]);
    }];
}

- (void)refresh {
    [self.options enumerateObjectsUsingBlock:^(SlideOptionCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.separatorItem = self.separator;
        [obj refresh];
    }];
}

- (void)setEdit:(BOOL)edit {
    _edit = edit;
    
    self.slider.highlighted = edit;
    [self.slider setNeedsLayout];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    NSUInteger lastCell = self.items.count - 1;
    if (lastCell >= 0 && lastCell < self.options.count && self.jk_width - self.options[lastCell].jk_right > 1) {
        [self relayoutLabels];
        [self refresh];
    }
}

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state {
    [self.colors setObject:color forKey:@(state)];
    
    [self.options enumerateObjectsUsingBlock:^(SlideOptionCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setTitleColor:color forState:state];
    }];
}

- (UIColor *)titleColorForState:(UIControlState)state {
    return [self.colors objectForKey:@(state)];
}

#pragma mark - Gesture
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint point = [gestureRecognizer locationInView:self.slider];
    return [self.slider.layer containsPoint:point] && self.edit;
}

#pragma mark - Action
- (void)panMove:(UIPanGestureRecognizer *)gr {
    CGPoint point = [gr translationInView:self];
    if (gr.state != UIGestureRecognizerStateEnded) {
        self.slider.transform = CGAffineTransformTranslate(self.slider.transform, point.x, 0);
        if ([self overlayWithLabel] != NSNotFound) {
            [self selectFeedback];
        }
    } else {
        NSUInteger closedIndex = [self findClosedLabelForSlider];
        self.slider.transform = CGAffineTransformIdentity;
        self.selectedIndex = closedIndex;
    }
    
    [gr setTranslation:CGPointZero inView:self];
}

- (void)clickOption:(SlideOptionCell *)sender {
    if (!self.edit) return;
    
    NSInteger index = [self.options indexOfObject:sender];
    self.selectedIndex = index;
}

#pragma mark - Private
- (void)selectFeedback {
    if (@available(iOS 10.0, *)) {
        static UISelectionFeedbackGenerator *selectFeedback = nil;
        if (!selectFeedback) {
            selectFeedback = [[UISelectionFeedbackGenerator alloc] init];
        }
        [selectFeedback selectionChanged];
    }
}

- (NSInteger)overlayWithLabel {
    CGFloat x = CGRectGetMidX(self.slider.frame);
    __block NSUInteger overlayIndex = NSNotFound;
    [self.options enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (fabs(CGRectGetMidX(obj.frame) - x) < 10e-1) {
            overlayIndex = idx;
        }
        *stop = obj.hidden || overlayIndex != NSNotFound;
    }];
    return overlayIndex;
}

- (NSInteger)findClosedLabelForSlider {
    CGFloat x = CGRectGetMidX(self.slider.frame);
    __block NSUInteger closedIndex = 0;
    [self.options enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (closedIndex != idx && fabs(CGRectGetMidX(obj.frame) - x) < fabs(CGRectGetMidX(self.options[closedIndex].frame) - x)) {
            closedIndex = idx;
        }
        
        *stop = obj.hidden;
    }];
    return closedIndex;
}

- (void)relayoutLabels {
    // 补充不足
    
    UIColor *selectColor = [self titleColorForState:UIControlStateSelected];
    UIColor *normalColor = [self titleColorForState:UIControlStateNormal];
    [[@(self.items.count - self.options.count) x_array] enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SlideOptionCell *label = [[SlideOptionCell alloc] init];
        [label addTarget:self action:@selector(clickOption:) forControlEvents:UIControlEventTouchUpInside];
        label.titleLabel.font = [UIFont systemFontOfSize:13];
        [label setTitleColor:normalColor forState:UIControlStateNormal];
        [label setTitleColor:selectColor forState:UIControlStateSelected];
        label.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.mas_offset(0);
        }];
        [self.options addObject:label];
    }];
    
    for (NSInteger i = 0; i < self.items.count; i++) {
        OptionItem *item = self.items[i];
        [self.options[i] setTitle:[self stringForItem:item] forState:UIControlStateNormal];
        self.options[i].hidden = NO;
    }
    // position
    CGFloat width = self.jk_width / self.items.count;
    if (width > 0) {
        [[self.options subarrayWithRange:NSMakeRange(0, self.items.count)] enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj mas_updateConstraints:^(MASConstraintMaker *make) {
                make.leading.mas_equalTo(idx * width);
                make.width.mas_equalTo(width);
            }];
        }];
    }
    
    [[self.options subarrayWithRange:NSMakeRange(self.items.count, self.options.count - self.items.count)] jk_each:^(UIButton *object) {
        object.hidden = YES;
    }];
}

@synthesize slider = _slider;
- (SlideOptionViewSlider *)slider {
    if (!_slider) {
        _slider = [[SlideOptionViewSlider alloc] init];
    }
    return _slider;
}

- (FSeparatorItem *)separator {
    if (!_separator) {
        _separator = [[FSeparatorItem alloc] init];
    }
    return _separator;
}

@end
